package com.andox.fn.inf.rpc.rest.cluster.loadbalance;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import com.andox.fn.inf.rpc.rest.exception.ServiceRuntimeException;
import com.andox.fn.inf.rpc.rest.filter.Invoker;

public class RobinInvokerSelector implements InvokerSelector{
	private AtomicInteger lastIndex = new AtomicInteger(0);
	
	@Override
	public Invoker selectInvoker(List<Invoker> invokerList) {
		return this.next(invokerList, this.lastIndex.incrementAndGet());
	}
	
	private Invoker next(List<Invoker> invokerList, int last) {
		if (invokerList == null || invokerList.size() == 0) {
			throw new ServiceRuntimeException("there are no validate provider.");
		}
		int length = invokerList.size();
		if (last > length - 1) {
			last = 0;
		}
		
		return invokerList.get(last);
	}
}
